package web.service.impls;

import java.util.List;

import map.beans.GeneralConfigBean;
import map.constants.MapDefaultPropertyValues;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import web.dao.interfaces.AdditionalConfigDao;
import web.service.interfaces.AdditionalConfigServiceInterface;

@Repository("additionalConfigService")
public class AdditionalConfigServiceImpl implements AdditionalConfigServiceInterface {
	private static Logger LOGGER = LoggerFactory.getLogger(AdditionalConfigServiceImpl.class);
	@Autowired
	AdditionalConfigDao addDao;

	@Override
	public Long update(GeneralConfigBean genConfig) {
		return addDao.update(genConfig);
	}

	@Override
	public GeneralConfigBean getDefaultConfig() {
		GeneralConfigBean config = addDao.getDefaultConfig();
		try {
			if (config == null || config.getId() == null) {
				registerDefaultConfiguration();
				config = addDao.getDefaultConfig();
			}
		} catch (Exception e) {
			LOGGER.error(e.getMessage());
		}		
		
		return config;
	}

	@Override
	public List<GeneralConfigBean> findAll() {
		List<GeneralConfigBean> genConfig = addDao.findAll();
		try {
			if (genConfig == null || genConfig.isEmpty()) {
				registerDefaultConfiguration();
				genConfig = addDao.findAll();
			}
		} catch (Exception e) {
			LOGGER.error(e.getMessage());
		}		
		return genConfig;
	}

	@Override
	public void delete(GeneralConfigBean config) {	
		addDao.delete(config);
	}	

	private void registerDefaultConfiguration() {
		GeneralConfigBean gc = new GeneralConfigBean();
		
		gc.setLat(MapDefaultPropertyValues.APG_LAT);
		gc.setLon(MapDefaultPropertyValues.APG_LNG);
		gc.setScale(MapDefaultPropertyValues.DEFAULT_SCALE);
		
		update(gc);
	}
}
